import { useDispatch } from 'react-redux'
import { Button, Checkbox, Form, Input } from 'antd'
import './index.scss'
import { IconPassword, IconUser } from '@/components/icon/index.jsx'
import { useState } from 'react'
import { login } from '@/api/auth/user.js'
import { setToken } from '@/store/slices/userSlice.jsx'
import { useNavigate } from 'react-router-dom'
import { message } from 'antd'

const Login = () => {
  const [loading, setLoading] = useState(false)
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const [messageApi, contextHolder] = message.useMessage()

  const handLogin = (values) => {
    setLoading(true)
    login(values)
      .then((res) => {
        if (res.code === 200) {
          setLoading(false)
          dispatch(setToken(res.data?.token))
          // 跳转首页
          navigate('/home')
        } else {
          setLoading(false)
          messageApi.open({
            type: 'error',
            content: res.message
          })
        }
      })
      .finally(() => {
        setLoading(false)
      })
  }
  return (
    <div className={'login-wrapper'}>
      {contextHolder}
      <div className='login-box'>
        <div className={'login-box-title'}>
          <p className={'title'}>Omnitrix ERP系统</p>
          <p className={'welcome'}>账 号 登 录</p>
        </div>
        <Form className={'login-box-form'} onFinish={handLogin}>
          <Form.Item
            name='username'
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input type='text' prefix={<IconUser />} placeholder={'用户名'} />
          </Form.Item>
          <Form.Item
            name='password'
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password prefix={<IconPassword />} placeholder={'密码'} />
          </Form.Item>
          <Form.Item>
            <Form.Item
              name='rememberMe'
              valuePropName='checked'
              className={'no-margin fl'}
            >
              <Checkbox>记住我</Checkbox>
            </Form.Item>
            <Form.Item className={'no-margin fr'}>
              <a href=''>忘记密码？</a>
            </Form.Item>
          </Form.Item>
          <Form.Item>
            <Button
              className={'login-btn'}
              type='primary'
              htmlType='submit'
              loading={loading}
            >
              登 录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
